# -*- coding: utf-8 -*-
# @Author: Administrator
# @Date:   2018-02-04 09:29:05
# @Last Modified by:   Administrator
# @Last Modified time: 2018-02-04 09:38:02
# -*- coding: utf-8 -*-
#python 爬虫有道翻译
import requests
from bs4 import BeautifulSoup
import json
f=open('翻译文本.txt','r') 
f1=open('翻译结果.txt','w+')
content=f.readline()
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionFrom=null'
headers = {
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
    ,'from':'AUTO',
    'to':'AUTO',
    'smartresult':'dict',
    'client':'fanyideskweb',
    'doctype':'json',
    'version':'2.1',
    'keyfrom':'fanyi.web',
    'action':'FY_BY_ENTER',
    'typoResult':'true',    
    'i':content
    ,'ue':'UTF-8'#设置翻译支持中文
}
while len(headers[u'i'])>0:
    res = requests.get(url,params = headers)
    soup = BeautifulSoup(res.text,'lxml')
    jd = json.loads(soup.text)
    for translate in jd['translateResult'][0]:
        print(translate[u'tgt'])
        f1.write(translate[u'tgt']+'\n')
    headers[u'i']=f.readline()
    
input('按任意键以退出')
f.close()
f1.close()